//
//  StatusPhotos.swift
//  SinaWeibo
//
//  Created by 郭平 on 15/10/18.
//  Copyright © 2015年 郭平. All rights reserved.
//

import UIKit

private let PHOTO_MAX_COUNT = 9         // 图片最大的张数
private let PHOTO_MARGIN: CGFloat = 10  // 图片间距
private let MAX_Col = 3                 // 多少行

class StatusPhotos: UIView {

    // 设置数据
    var pic_urls: [StatusPhotoInfo]? {
        
        didSet{
            setPicUrls()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        for _ in 0..<9 {
            
            let imageView = StatusPhotoImageView(frame: CGRectZero)
            
            addSubview(imageView)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 根据有多少张图片,显示多少个imageView
    private func setPicUrls() {
        
        for chilView in subviews {
            chilView.hidden = true
        }
        
        for i in 0..<pic_urls!.count {
            let childView = subviews[i] as! StatusPhotoImageView
            childView.hidden = false
            
            let info = pic_urls![i]
            childView.thumbnail_pic = info.thumbnail_pic
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        if pic_urls == nil {
            
            return
        }
        
        let childViewWH = (SCREENW - 4 * PHOTO_MARGIN) / CGFloat(MAX_Col)
        
        let tempCol = pic_urls!.count == 4 ? 2 : MAX_Col
        
        for i in 0..<pic_urls!.count {
            
            let childView = subviews[i]
            
            let col = i % tempCol       // 控制器第几列
            let row = i / tempCol       //      第几行
            
            let childViewX = CGFloat(col) * (childViewWH + PHOTO_MARGIN)
            let childViewY = CGFloat(row) * (childViewWH + PHOTO_MARGIN)
            
            childView.frame = CGRect(x: childViewX, y: childViewY, width: childViewWH, height: childViewWH)
        }
    }
    
    /**
    根据图片的个数,计算当前View的大小
    
    - parameter count: 图片的个数
    
    - returns: 返回View大小
    */
    class func size(count: Int) ->CGSize {
        
        let row = (count - 1) / MAX_Col + 1
        
        // 计算每个子控件的宽度
        let childViewWH = (SCREENW - 4 * PHOTO_MARGIN) / CGFloat(MAX_Col)
        // 计算米格子控件高度
        let viewH = CGFloat(row) * childViewWH + CGFloat(row - 1) * PHOTO_MARGIN
        let viewW = SCREENW - CELL_CHILD_VIEW_MARGIN * 2
        
        return CGSizeMake(viewW, viewH)
    }
    
}
